package com.elastic.eslearn._3_search;

import com.elastic.eslearn._0_client.EsUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;

/**
 * matchQuery 示例
 */
public class EsMatchQuery {
	public static void main(String[] args) throws Exception {
		QueryBuilder matchQuery = QueryBuilders.matchQuery("title", "python")
				.operator(Operator.AND);
		HighlightBuilder highlightBuilder = new HighlightBuilder()
				.field("title")
				.preTags("<span stype=\"color:red\">")
				.postTags("</span>");

		SearchResponse searchResponse = EsUtils.getSingleClient()
				.prepareSearch("books")
				.setQuery(matchQuery)
				.highlighter(highlightBuilder)
				.setSize(100)
				.get();
		SearchHits searchHits = searchResponse.getHits();
		System.out.println("共搜索到：" + searchHits.getTotalHits() + " 条数据");
		for (SearchHit hit : searchHits) {
			System.out.println("Source: " + hit.getSourceAsString());
			System.out.println("Source As Map: " + hit.getSourceAsMap());
			Text[] textArr = hit.getHighlightFields().get("title").getFragments();
			for (Text str : textArr) {
				System.out.println(str.toString());
			}
		}
	}
}
